package com.bdqn.controller;


import com.bdqn.pojo.User;
import com.bdqn.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class IndexController {
    @Resource
    private IUserService userService;

    @RequestMapping(value = "/index")

    public String index() {
        return "login";
    }

    @RequestMapping(value = "/main")
    public String main() {
        return "main";
    }

    @RequestMapping(value = "/login")
    public String login(String usrName, String usrPassword, Model model, HttpSession session) {
       /*User loginUser = userService.login(usrName, usrPassword);
         if (loginUser != null) {
             session.setAttribute("loginUser", loginUser);
            return "redirect:/main";//建议重定向
             }else{
         } model.addAttribute("msg","用户名或密码错误，登录失败！");
         return "login";//必须转发
        }*/
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(usrName, usrPassword);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);//认证、登录
       /*     //认证(登录)成功
            User user = (User) subject.getPrincipal();
            //获取权限
            Role role = user.getRole();
            List<Right> rights = roleService.findRightsByRole(role);
            role.getRights().addAll(rights);
            session.setAttribute("loginUser", user);
            //清空权限缓存
            RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
            MyShiroRealm realm = (MyShiroRealm) rsm.getRealms().iterator().next();
            realm.clearMyCachedAuthorizationInfo();*/
            //认证(登录)成功
            User user = (User) subject.getPrincipal();
            session.setAttribute("loginUser", user);
            return "redirect:/main";//建议重定向
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            model.addAttribute("msg", "用户名或密码错误，登录失败！");
            return "login";
        } catch (LockedAccountException e) {
            model.addAttribute("msg", "用户被禁用，登录失败！");
            return "login";
        } catch (AuthenticationException e) {
            model.addAttribute("msg", "认证异常，登录失败！");
            return "login";
        }
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        SecurityUtils.getSubject().logout();//Shiro注销
        return "redirect:/main";//建议重定向，保证删除Cookie
    }

    @RequestMapping(value = "/403")
    public String unauthorized() {
        return "403";
    }
}
